package concurrent.result;

import concurrent.domain.Result;
import concurrent.domain.Slave;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class ResultByCountDownLatch {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println(System.currentTimeMillis());
        CountDownLatch countDownLatch = new CountDownLatch(2);
        Result<List<Slave>> result = new Result<>();
        result.setResult(new ArrayList<>(2));
        //创建一个子线程
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                Slave slave = new Slave();
                slave.setName("杨玉帆");
                slave.setAge(18);
                slave.setDesc("杨玉帆喜欢口交");
                result.getResult().add(slave);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                countDownLatch.countDown();
            }
        });
        thread.start();
        //创建一个子线程
        Thread thread2 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(4);
                Slave slave = new Slave();
                slave.setName("陈婉红");
                slave.setAge(19);
                slave.setDesc("陈婉红是小母狗");
                result.getResult().add(slave);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                countDownLatch.countDown();
            }
        });
        thread2.start();
        //countDownLatch.await()会让当前线程阻塞，当countDownLatch中的计数器变为0的时候，await方法会返回
        countDownLatch.await();

        //获取thread线程的执行结果
        System.out.println(System.currentTimeMillis());
        System.out.println(System.currentTimeMillis() + ":" + result.getResult());
    }

}
